package com.cms.teacher;


import com.auxiliary.Util;
import com.doman.*;
import com.resultmsg.BaseEnums;
import com.resultmsg.Result;
import com.resultmsg.Results;
import com.server.BaseConfigMapper;
import com.server.TeacherMapper;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RequestMapping(value = "/educloud")
@RestController
public class TeachersController {

    @Autowired
    private TeacherMapper mapper;

    @Autowired
    private BaseConfigMapper baseConfigMapper;

    /**
     * 条件搜索
     *
     * @param stuConditions
     * @return
     */
    @RequestMapping(value = "/teachers/conditions", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Result getStudentsByCondition(@RequestBody TeaConditions stuConditions) {
        try {

            List<Teacher> list = mapper.selectByCondition(stuConditions);
            if (list.size() > 0) {
                return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            } else {
                return Results.failureWithData("", BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());

            }
        } catch (Exception e) {
            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }
    }

    /**
     * 全局搜索
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/teachers", method = RequestMethod.GET)
    public Result getStudents() {
//        try {
        List<Teacher> list = mapper.selectAll();
        return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
//        } catch (Exception e) {
//            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
//        }
    }

    /**
     * 添加学生
     *
     * @param teacher
     * @return
     */
    @RequestMapping(value = "/teachers", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Result addStudent(@RequestBody Teacher teacher) {

//        try {

        if (teacher.getBindcode().isEmpty()) {
            teacher.setBindcode(Util.getKcode("", 6));
        }

        int res = mapper.insertSelective(teacher);
        if (res > 0)
            return Results.successWithData(teacher, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        else
            return Results.failureWithData(res, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
//        } catch (Exception e) {
//            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
//        }
    }

    /**
     * 更新学生
     *
     * @param teacher
     * @return
     */
    @RequestMapping(value = "/teachers", method = RequestMethod.PUT, produces = {"application/json;charset=UTF-8"})
    public Result updateStudent(@RequestBody Teacher teacher) {

        try {
            int res = mapper.updateByPrimaryByCodeUpdate(teacher);
            if (res > 0)
                return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            else
                return Results.failure(BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        } catch (Exception e) {
            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }
    }

    /**
     * 删除学生
     *
     * @param bindcode
     * @return
     */
    @RequestMapping(value = "/teachers/{bindcode}", method = RequestMethod.DELETE)
    public Result delStudent(@PathVariable("bindcode") String bindcode) {
        try {
//        System.out.println("bindcode="+bindcode);
            int res = mapper.delByBindCode(bindcode);
            if (res > 0)
                return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            else
                return Results.failure(BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        } catch (Exception e) {
            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }
    }


    @RequestMapping(value = "/uploadTeacher/{bindcode}", method = RequestMethod.POST)
    public Result upload(@RequestBody MultipartFile file,@PathVariable("bindcode") String bindcode) throws IOException {
        System.out.println("bindcode==" + bindcode);

//        List<BaseConfig > baseConfigs = getAllKcode();
//        List<BaseConfig> baseConfigs = baseConfigMapper.selectByType("grade");

        InputStream in = null;

        System.out.println("file==" + file);
        try {
            //将file转InputStream
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将InputStream转XLSX对象（即表格对象）
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
        //获取表格的第一页
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        //获取该页有多少数据
        int rowNum = xssfSheet.getLastRowNum();
        System.out.println("该页有多少数据：" + rowNum);
        int addcount = 0;
        if (rowNum < 1)
            return Results.failureWithData("无有效数据", BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());

        List<Teacher> teacherList = new ArrayList<>();

        try {
            for (int i = 1; i <= rowNum; i++) {
                Teacher teacher = new Teacher();
                //获取当前行
                XSSFRow xssfRow = xssfSheet.getRow(i);

                //序号
                if (xssfRow.getCell(0) != null)
                    xssfRow.getCell(0).setCellType(CellType.STRING);
                //icon
                if (xssfRow.getCell(1) != null) {
                    xssfRow.getCell(1).setCellType(CellType.STRING);
                    String icon = xssfRow.getCell(1).toString().trim();
                    if (icon.length() > 255)
                        throw new Exception("第" + i + "行【头像】地址过长");
                    else
                        teacher.setIcon(icon);
                }
                //name
                if (xssfRow.getCell(2) != null) {
                    xssfRow.getCell(2).setCellType(CellType.STRING);
                    String name = xssfRow.getCell(2).toString().trim();
//                    System.out.println("name：" + name);
                    if (name.equals("")) {
                        throw new Exception("第" + i + "行【姓名】不能为空");
                    } else{
                        if (name.length() <= 16) {
                            teacher.setName(name);
                        } else {
                            teacher.setName(name.substring(0, 16));
                        }
                    }
                } else {
                    //逻辑说明：姓名为空则认为数据结束
//                    throw new Exception("第" + i + "行【姓名】不能为空");
                    break;
                }

                //sex
                if (xssfRow.getCell(3) != null) {
                    xssfRow.getCell(3).setCellType(CellType.STRING);
                    int sex = xssfRow.getCell(3).toString().equals("男") ? 0 : 1;
                    teacher.setSex(sex);
                } else {
                    teacher.setSex(0);
                }
                //subject
                if (xssfRow.getCell(4) != null) {
                    xssfRow.getCell(4).setCellType(CellType.STRING);
                    String subject = xssfRow.getCell(4).toString().trim();
                    if (subject.length() < 16) {
                        teacher.setTel(subject);
                    } else {
                        teacher.setSubject(subject.substring(0,16));
                    }
                }
                //tel
                if (xssfRow.getCell(5) != null) {
                    xssfRow.getCell(5).setCellType(CellType.STRING);
                    String tel = xssfRow.getCell(5).toString().trim();
                    if (tel.length() < 11) {
                        teacher.setTel(tel);
                    } else {
                        teacher.setTel(tel.substring(0, 11));
                    }
                }else{
                    throw new Exception("第" + i + "行【手机号】不能为空");
                }
                //description
                if (xssfRow.getCell(6) != null) {
                    xssfRow.getCell(6).setCellType(CellType.STRING);
                    String description = xssfRow.getCell(6).toString().trim();
                    if (description.length() > 300)
                        throw new Exception("第" + i + "行【个人简介】长度超出");
                    else
                        teacher.setDescription(description);

                }
                //organize
//                if (xssfRow.getCell(7) != null) {
//                    xssfRow.getCell(7).setCellType(CellType.STRING);
//                    String organize = xssfRow.getCell(7).toString().trim();
//                    if (organize.equals(""))
//                        throw new Exception("第" + i + "【组织结构】不能为空");
//                    else
//                        teacher.setOrganize(organize);
//                } else {
//                    throw new Exception("第" + i + "【组织结构】不能为空");
//                }
                if(bindcode==null||bindcode.equals(""))
                    throw new Exception("第" + i + "行【组织结构】不能为空");
                teacher.setOrganize(bindcode.trim());
                teacher.setCreateTime(Util.getCurrentTime());
                teacher.setUpdateTime(Util.getCurrentTime());
                teacherList.add(teacher);

                //由于学号是纯数字，默认纯数字是以double传的，写进据库会变成科学计数法格式的，需要改为以string传进来
//            if (xssfRow.getCell(1).equals("") || xssfRow.getCell(1) == null)



//            }catch (Exception e){
//                System.out.println(e.toString());
//                return Results.failureWithData("第"+i+"行数据异常", BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());
//
//            }

                //将实体类插入数据库
//           addStudent(student);
//            System.out.println("sno:::"+student+"name:::"+"clbun:::"+clbun+"node:::"+node);
//            System.out.println("批量：" + student.getBindcode());

//            if (null == teacher.getBindcode() || "".equals(teacher.getBindcode())) {
//                teacher.setBindcode(Util.getKcode("", 6));
//            }
//            int res = mapper.insertSelective(teacher);
//            if(res>0)
//                addcount++;
                //防止重复插入
//                int res = 0;
//                do {
//                    res = insertTeacher(teacher);
//                    if (res > 0) {
//                        addcount++;
//                    }
//                } while (res <= 0);
//
//
//                System.out.println("批量导入：" + res);
            }
        } catch (Exception e) {
//            System.out.println("catch::" + e.toString());
            return Results.failureWithData("Excel::" + e.toString(), BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());
        }

        try {

            for (int i = 0; i <teacherList.size() ; i++) {
                //防止重复插入
                int res = 0;
                do {
                    res = insertTeacher(teacherList.get(i));
                    if (res > 0) {
                        addcount++;
                    }
                } while (res <= 0);
//
            }
        }catch (Exception e){
            return Results.failureWithData("SQL::" + e.toString(), BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());

        }

        return Results.successWithData(addcount, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
    }


    private int insertTeacher(Teacher teacher) {
        if (null == teacher.getBindcode() || "".equals(teacher.getBindcode())) {
            teacher.setBindcode(Util.getKcode("", 6));
        }
        int res = mapper.insertSelective(teacher);
        return res;
    }


}
